<template>
	<div class="wrapper">

		<!-- header部分 -->
		<header>
			<p><Back></Back>在线支付</p>
		</header>

		<!-- 订单信息部分 -->
		<h3>订单信息：</h3>
		<div class="order-info">
			<p>
				{{orders.business.businessName}}
				<i class="fa fa-caret-down" @click="detailetShow"></i>
			</p>
			<p>&#165;{{orders.orderTotal}}</p>
		</div>

		<!-- 订单明细部分 -->
		<ul class="order-detailet" v-show="isShowDetailet">
			<li v-for="item in orders.list" :key="item.food.foodId">
				<p>{{item.food.foodName}} x {{item.quantity}}</p>
				<p>&#165;{{item.food.foodPrice*item.quantity}}</p>
			</li>
			<li>
				<p>配送费</p>
				<p>&#165;{{orders.business.deliveryPrice}}</p>
			</li>
		</ul>

		<!-- 支付方式部分 -->
		<h3>选择支付方式：</h3>
		<ul class="payment-type">
			<li @click="selectPayment('wallet')" :class="{ active: paymentMethod === 'wallet' }">
				<div class="payment-icon">
					<i class="fa fa-credit-card"></i>
					<span>钱包支付</span>
				</div>
				<i class="fa fa-check-circle" v-if="paymentMethod === 'wallet'"></i>
			</li>
			<li @click="selectPayment('alipay')" :class="{ active: paymentMethod === 'alipay' }">
				<div class="payment-icon">
					<img src="../assets/alipay.png">
				</div>
				<i class="fa fa-check-circle" v-if="paymentMethod === 'alipay'"></i>
			</li>
			
		</ul>
		
		<!-- 钱包支付密码输入框 -->
		<div class="wallet-payment" v-if="paymentMethod === 'wallet'">
			<div class="wallet-balance" v-if="walletInfo">
				<p>钱包余额：<span :class="{ 'insufficient': orders.orderTotal > walletInfo.balance }">&#165;{{walletInfo.balance}}</span></p>
				<p v-if="orders.orderTotal > walletInfo.balance" class="balance-warning">
					余额不足，请充值
				</p>
			</div>
			<div class="wallet-password">
				<label>支付密码</label>
				<input type="password" v-model="payPassword" placeholder="请输入钱包支付密码" maxlength="6">
			</div>
		</div>
		
		<div class="payment-button">
			<button @click="processPayment()" :disabled="isPayButtonDisabled">确认支付</button>
		</div>

		<!-- 钱包创建提示框 -->
		<div class="dialog-overlay" v-if="showCreateWalletDialog">
			<div class="dialog-container">
				<div class="dialog-header">
					<h3>您还未创建钱包</h3>
					<span @click="showCreateWalletDialog = false" class="dialog-close">&times;</span>
				</div>
				<div class="dialog-content">
					<p>您需要先创建钱包才能使用钱包支付</p>
				</div>
				<div class="dialog-footer">
					<button @click="toCreateWallet" class="dialog-btn">去创建钱包</button>
				</div>
			</div>
		</div>

		<!-- 充值提示框 -->
		<div class="dialog-overlay" v-if="showRechargeDialog">
			<div class="dialog-container">
				<div class="dialog-header">
					<h3>余额不足</h3>
					<span @click="showRechargeDialog = false" class="dialog-close">&times;</span>
				</div>
				<div class="dialog-content">
					<p>您的钱包余额不足以支付此订单</p>
					<div class="recharge-info">
						<p>订单金额：<span>&#165;{{orders.orderTotal}}</span></p>
						<p>钱包余额：<span>&#165;{{walletInfo ? walletInfo.balance : 0}}</span></p>
						<p>还需充值：<span class="insufficient">&#165;{{neededAmount}}</span></p>
					</div>
				</div>
				<div class="dialog-footer">
					<button @click="toRechargeWallet" class="dialog-btn">去充值</button>
				</div>
			</div>
		</div>

		<!-- 底部菜单部分 -->
		<Footer></Footer>
	</div>
</template>

<script>
	import Footer from '../components/Footer.vue';
import Back from '../components/Back.vue';
	export default {
	    name: 'Payment',
	    data() {
	        return {
	            orderId: this.$route.query.orderId,
	            orders: {
	                business: {}
	            },
	            isShowDetailet: false,
				
				// 支付方式
				paymentMethod: 'alipay',
				
				// 钱包相关
				user: null,
				walletInfo: null,
				walletId: null,
				payPassword: '',
				
				// 对话框控制
				showCreateWalletDialog: false,
				showRechargeDialog: false
	        };
	    },
	    computed: {
			isPayButtonDisabled() {
				// 如果是钱包支付，需要验证密码和余额
				if (this.paymentMethod === 'wallet') {
					// 如果没有钱包或者余额不足
					if (!this.walletInfo) {
						return true;
					}
					
					// 如果余额不足
					if (this.walletInfo.balance < this.orders.orderTotal) {
						return true;
					}
					
					// 如果没有输入密码
					return this.payPassword.length !== 6;
				}
				
				return false;
			},
			
			neededAmount() {
				if (!this.walletInfo || !this.orders.orderTotal) {
					return 0;
				}
				
				return (this.orders.orderTotal - this.walletInfo.balance).toFixed(2);
			}
		},
	    created() {
			// 获取用户和订单信息
			this.user = this.$getSessionStorage('user');
			
			let url = `OrdersController/getOrdersById/${this.orderId}`;
	        this.$axios.get(url).then(response => {
	            this.orders = response.data.result;
				
				// 如果用户已登录，获取钱包信息
				if (this.user) {
					this.checkWallet();
				}
	        }).catch(error => {
	            console.error(error);
	        });
	    },
	    mounted() {
	        // 实现不允许返回订单确认组件的逻辑
	        history.pushState(null, null, document.URL);
	        window.onpopstate = () => {
	            this.$router.push({ path: '/index' });
	        };
	    },
	    unmounted() {
	        window.onpopstate = null;
	    },
	    methods: {
	        detailetShow() {
	            this.isShowDetailet = !this.isShowDetailet;
	        },
			
			// 选择支付方式
			selectPayment(method) {
				this.paymentMethod = method;
				
				// 如果选择钱包支付，检查钱包是否存在
				if (method === 'wallet') {
					if (!this.walletInfo) {
						this.showCreateWalletDialog = true;
					} else if (this.walletInfo.balance < this.orders.orderTotal) {
						this.showRechargeDialog = true;
					}
				}
			},
			
			// 检查钱包
			checkWallet() {
				// 这里假设钱包ID和用户ID一致，如果后端不一致需要调整
				this.walletId = this.user.userId;
				
				// 尝试获取钱包信息
				this.$axios.get(`WalletController/getWallet/${this.walletId}`)
					.then(response => {
						if (response.data.code === 200 && response.data.result) {
							this.walletInfo = response.data.result;
							// 获取余额
							this.getBalance();
						}
					})
					.catch(error => {
						console.error('获取钱包信息失败', error);
						this.walletInfo = null;
					});
			},
			
			// 获取余额
			getBalance() {
				this.$axios.get(`WalletController/getBalance/${this.walletId}`)
					.then(response => {
						if (response.data.code === 200) {
							this.walletInfo.balance = response.data.result;
						}
					})
					.catch(error => {
						console.error('获取余额失败', error);
					});
			},
			
			// 处理支付
			processPayment() {
				if (this.paymentMethod === 'wallet') {
					this.walletPayment();
				} else {
					this.toSuccess();
				}
			},
			
			// 钱包支付
			walletPayment() {
				// 获取商家钱包ID（这里假设是商家用户ID）
				const businessWalletId = this.orders.business.businessId;
				
				// 发起转账请求
				this.$axios.post(`WalletController/transfer/${this.walletId}/${businessWalletId}/${this.orders.orderTotal}/${this.payPassword}`)
					.then(response => {
						if (response.data.code === 200) {
							// 转账成功后，更新订单状态
							this.updateOrderStatus();
						} else {
							// 处理转账失败
							alert('支付失败: ' + response.data.message);
						}
					})
					.catch(error => {
						console.error('支付失败', error);
						alert('支付失败，请检查支付密码或稍后重试');
					});
			},
			
			// 更新订单状态
			updateOrderStatus() {
				// 构造请求数据
				const payload = {
					orderId: this.orderId
				};
				
				// 发送更新订单状态的请求
				this.$axios.post('OrdersController/payOrdersById', this.$qs.stringify(payload))
					.then(() => {
						// 支付成功，跳转到成功页面
						this.$router.push({ path: '/successPayment', query: { orderId: this.orderId } });
					})
					.catch(error => {
						console.error('更新订单状态失败', error);
						alert('支付已完成，但更新订单状态失败，请联系客服');
					});
			},
			
			// 原有的支付完成方法
			toSuccess() {
				// Construct the request payload
				const payload = {
					orderId: this.orderId
				};
				
				// Make a POST request to the backend to confirm payment
				this.$axios.post('OrdersController/payOrdersById', this.$qs.stringify(payload))
					.then(() => {	                
						this.$router.push({ path: '/successPayment', query: { orderId: this.orderId } }); 	                
					})
					.catch(error => {
						// Handle any errors that occur during the request
						console.error('Error during payment confirmation:', error);
					});
			},
			
			// 跳转到钱包创建页面
			toCreateWallet() {
				this.$router.push({ path: '/myWallet' });
			},
			
			// 跳转到钱包充值页面
			toRechargeWallet() {
				this.$router.push({ path: '/myWallet' });
			}
	    },
	    components: {
	        Footer,
			Back
	    }
	}
</script>

<style scoped>
	/****************** 总容器 ******************/
	.wrapper {
		width: 100%;
		height: 100%;
	}

	/****************** header部分 ******************/
	.wrapper header {
		width: 100%;
		height: 12vw;
		background-color: #0097FF;
		color: #fff;
		font-size: 4.8vw;

		position: fixed;
		left: 0;
		top: 0;
		z-index: 1000;

		display: flex;
		justify-content: center;
		align-items: center;
	}

	/****************** 订单信息部分 ******************/
	.wrapper h3 {
		margin-top: 12vw;
		box-sizing: border-box;
		padding: 4vw 4vw 0;

		font-size: 4vw;
		font-weight: 300;
		color: #999;
	}

	.wrapper .order-info {
		box-sizing: border-box;
		padding: 4vw;
		font-size: 4vw;
		color: #666;

		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.wrapper .order-info p:last-child {
		color: orangered;
	}

	/****************** 订单明细部分 ******************/
	.wrapper .order-detailet {
		width: 100%;
	}

	.wrapper .order-detailet li {
		width: 100%;
		box-sizing: border-box;
		padding: 1vw 4vw;

		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.wrapper .order-detailet li p {
		font-size: 3vw;
		color: #666;
	}

	/****************** 支付方式部分 ******************/
	.wrapper .payment-type {
		width: 100%;
		margin-top: 2vw;
	}

	.wrapper .payment-type li {
		width: 100%;
		box-sizing: border-box;
		padding: 3vw 4vw;
		margin-bottom: 2vw;
		background-color: #fff;
		border-radius: 2px;
		border-left: 4px solid transparent;

		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.wrapper .payment-type li.active {
		border-left: 4px solid #38CA73;
	}
	
	.payment-icon {
		display: flex;
		align-items: center;
	}
	
	.payment-icon i {
		font-size: 6vw;
		color: #0097FF;
		margin-right: 3vw;
	}
	
	.payment-icon span {
		font-size: 4vw;
		color: #333;
	}

	.wrapper .payment-type li img {
		width: 33vw;
		height: 8.9vw;
	}

	.wrapper .payment-type li .fa-check-circle {
		font-size: 5vw;
		color: #38CA73;
	}
	
	/****************** 钱包支付部分 ******************/
	.wallet-payment {
		margin-top: 4vw;
		padding: 0 4vw;
	}
	
	.wallet-balance {
		background-color: #fff;
		padding: 3vw;
		border-radius: 4px;
		margin-bottom: 3vw;
	}
	
	.wallet-balance p {
		font-size: 3.8vw;
		color: #666;
	}
	
	.wallet-balance .insufficient {
		color: #FF5252;
	}
	
	.balance-warning {
		color: #FF5252 !important;
		font-size: 3.5vw !important;
		margin-top: 1vw;
	}
	
	.wallet-password {
		background-color: #fff;
		padding: 3vw;
		border-radius: 4px;
	}
	
	.wallet-password label {
		display: block;
		font-size: 3.8vw;
		color: #333;
		margin-bottom: 2vw;
	}
	
	.wallet-password input {
		width: 100%;
		padding: 2.5vw;
		border: 1px solid #eee;
		border-radius: 4px;
		font-size: 3.8vw;
		box-sizing: border-box;
	}

	/****************** 支付按钮部分 ******************/
	.wrapper .payment-button {
		width: 100%;
		box-sizing: border-box;
		padding: 4vw;
		margin-top: 5vw;
		margin-bottom: 100vw; /* 添加底部边距，确保按钮不被Footer遮挡 */
	}

	.wrapper .payment-button button {
		width: 100%;
		height: 10vw;
		border: none;
		/*去掉外轮廓线*/
		outline: none;
		border-radius: 4px;
		background-color: #38CA73;
		color: #fff;
	}
	
	.wrapper .payment-button button:disabled {
		background-color: #cccccc;
	}
	
	/****************** 对话框样式 ******************/
	.dialog-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0,0,0,0.5);
		z-index: 2000;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.dialog-container {
		width: 80%;
		background-color: #fff;
		border-radius: 8px;
		overflow: hidden;
	}

	.dialog-header {
		padding: 3vw 4vw;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1px solid #f0f0f0;
	}

	.dialog-header h3 {
		font-size: 4.5vw;
		color: #333;
		margin: 0;
		padding: 0;
	}

	.dialog-close {
		font-size: 6vw;
		color: #999;
		cursor: pointer;
	}

	.dialog-content {
		padding: 4vw;
	}
	
	.dialog-content p {
		font-size: 3.8vw;
		color: #666;
		text-align: center;
		margin-bottom: 2vw;
	}
	
	.recharge-info {
		background-color: #f9f9f9;
		padding: 3vw;
		border-radius: 4px;
		margin-top: 3vw;
	}
	
	.recharge-info p {
		text-align: left;
		margin-bottom: 2vw;
		display: flex;
		justify-content: space-between;
	}
	
	.recharge-info p:last-child {
		margin-bottom: 0;
		padding-top: 2vw;
		border-top: 1px dashed #ddd;
	}
	
	.recharge-info .insufficient {
		color: #FF5252;
		font-weight: bold;
	}

	.dialog-footer {
		padding: 3vw 4vw;
		border-top: 1px solid #f0f0f0;
	}

	.dialog-btn {
		width: 100%;
		padding: 2.5vw;
		background-color: #0097FF;
		color: #fff;
		border: none;
		border-radius: 4px;
		font-size: 4vw;
	}
</style>
